package org.jeecg.modules.htxincailiao.crawler.processor;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LocalFileUtils {

    public static void main(String[] args) throws Exception {
        System.out.println(new LocalFileUtils("E:\\temp").saveFileToLocal("https://mp.ofweek.com/Upload/News/Img/member46034/202412/10132719935445.jpg", "https://xincailiao.ofweek.com"));
    }

    private final String uploadPath;

    public LocalFileUtils(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    public String saveFileToLocal(String imageUrl, String refererValue) throws Exception {
        String bizPath = "files";
        String nowDay = new SimpleDateFormat("yyyyMMdd").format(new Date());

        //创建新文件
        File file = new File(uploadPath + File.separator + bizPath + File.separator + nowDay);
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }

        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

        String savePath = file.getPath() + File.separator + fileName;

        // 直接保存
        File saveFile = new File(savePath);

        // 创建URL对象
        URL url = new URL(imageUrl);
        // 通过ImageIO读取图片到BufferedImage对象
        BufferedImage image;
        if (StringUtils.isNotBlank(refererValue)) {
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Referer", refererValue);
            image = ImageIO.read(urlConnection.getInputStream());
        } else {
            image = ImageIO.read(url);
        }
        // 使用ImageIO将BufferedImage写入到文件
        ImageIO.write(image, FileUtil.getSuffix(fileName), saveFile);

        String dbpath = bizPath + File.separator + nowDay + File.separator + fileName;
        if (dbpath.contains("\\")) {
            dbpath = dbpath.replace("\\", "/");
        }
        return dbpath;
    }
}
